package im.oen.boot.common.utils;

import im.oen.boot.common.extend.SnowflakeIdWorker;

import java.math.BigDecimal;
import java.util.Random;

/**
 * UUID生成器
 *
 * @author Kevin.Xu
 */
public class UUID {

    private static SnowflakeIdWorker IDWORKER = null;
    private static final Random random = new Random();

    static {
        IDWORKER = new SnowflakeIdWorker(31, 31);
    }

    /**
     * 更新雪花算法的数据中心ID和工作ID
     *
     * @param datacenterId 数据中心ID
     * @param workId       工作ID
     */
    public static void updateIdWorker(int datacenterId, int workId) {
        IDWORKER = new SnowflakeIdWorker(workId, datacenterId);
    }

    /**
     * 雪花算法生成的LongId
     *
     * @return
     */
    public static long uid() {
        return IDWORKER.nextId();
    }

    /**
     * Java原生UUID字符串去除了-
     *
     * @return
     */
    public static String uuid() {
        return java.util.UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 原生UUID+雪花算法UID 并 MD5 后的值
     *
     * @return
     */
    public static String uuuid() {
        return Digest.MD5(String.format("%s-%s-%s", java.util.UUID.randomUUID().toString(), IDWORKER.nextId(), java.util.UUID.randomUUID().toString()));
    }

    /**
     * Not include Max
     *
     * @param max
     * @return
     */
    public static int random(int max) {
        return random.nextInt(max);
    }

    public static int random(int low, int max) {
        int r = max - low;
        return random.nextInt(r) + low;
    }

    public static BigDecimal randomBigDecimal(int low, int max) {
        return new BigDecimal(String.valueOf(random(low, max)));
    }
}
